     /**
 * 
 */
package server;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.color.ColorSpace;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.awt.image.MemoryImageSource;
import java.awt.image.PixelGrabber;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.RandomAccessFile;
import java.math.*;
import javax.imageio.ImageIO;
import java.io.DataInputStream;

/**
 * @author Jun
 *
 */
public class ImageReader {

	/**
	 * ���ļ��ж�ȡ���512*512*2��������ؾ���,֮��Ծ�����в�
	 * @param args
	 */
	public static void main(String[] args)throws Exception {

		
		readImage2Png();

//		ImageReader.CreateGrayImage();

		/*byte pix[] = new byte[1];
		int n = new_img.getWidth();
		int m = new_img.getHeight();
		double[][] matrix = new double[n][m];
		 
		     //swips the rows
		     for (int row = 0; row < n; ++row) {
			//swips the columns
		         for (int col = 0; col < m; ++col) {
		        	 
		          //matrix[row][col] = new_img.getRGB(row, col);
		        	 
//		           new_img.getRaster().getDataElements(row, col, pix);
//		           matrix[row][col] = pix[0];
		           matrix[row][col] = new_img.getRaster().getSample(row, col, 0);
		        	 
		           System.out.println("row " + row + " col " + col + " pixel " + matrix[row][col]);                     
			  }
		 }	*/


	}
	public static void readImage2Png()throws Exception{
		
		int width = 512;
		int height = 512;
		
		String path = "e:/N20031223G062731.img";
		String path2 = "e:/N20031223G062731.jpg";
		String path3 = "e:/05.jpg";
		String path4 = "e:/result1.png";
		
		
		int noise = 564;
		float k = 1.0909f;
		
		
		int[] sample = GetData(path);
		int r = 220;
		int x = 261;
		int y = 257;
		
		int[] masksimg = mask(r , x, y, sample);
		int tem = 0;
		int l = 2*r;
		width = height = l;
		
		int[] samplefloat = new int[width*height];
		
		for(int i = 0; i< l*l; i++){
			
		tem =  masksimg[i];
//		tem -= noise;
		if(tem<0)
				tem=0;

		tem = (int)((tem*k*256)/4000);		
		
//		samplefloat[i] = (tem/2000.0f);
//		samplefloat[i] = (tem*256/4000.0f);
//		samplefloat[i] = tem;
		samplefloat[i] = (255<<24)|(tem<<16)|(tem<<8)|tem;
		
	}
		
		
		
		BufferedImage new_img = new BufferedImage(width,height,BufferedImage.TYPE_USHORT_GRAY);
		
		WritableRaster raster = new_img.getRaster();
//		raster.setSamples(0, 0, width, height,0, samplefloat);
		raster.setPixels(0, 0, width, height, samplefloat);
		
//		Image img3 = Toolkit.getDefaultToolkit().createImage( new MemoryImageSource(width ,height ,samplefloat, 0, width)); 
//		Graphics2D g = (Graphics2D)new_img.getGraphics();
//		new_img.getGraphics().drawImage(img3, 0, 0, null);
		
		
		
//		new_img = rotate(61.1,new_img);
		
		
		
//		raster.setSamples(0, 0, width, height, 0, samplefloat);
//		raster.setPixels(0, 0, width, height, samplefloat);
//		raster.setSamples(0, 0, width, height,0, sample);
//		raster.setSamples(0, 0, width, height,0, masksimg);
//		BufferedImage grayImage = new BufferedImage(width,height,BufferedImage.TYPE_BYTE_GRAY);
//		Graphics2D g = grayImage.createGraphics();
//		g.drawImage(grayImage, null,null);
		try {
			
		File file = new File(path4);
		if (!file.exists())
			file.createNewFile();
		
		ImageIO.write(new_img, "png", file);

	} catch (RuntimeException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
		
		
		
	}
	/**
	 * read aurora image to Jpg file
	 */
	public static void readImage2Jpg()throws Exception{
		
		int width = 512;
		int height = 512;
		
		String path = "e:/N20031223G062731.img";
		String path2 = "e:/N20031223G062731.jpg";
		String path3 = "e:/05.jpg";
		String path4 = "e:/result1.jpg";
		
		
		int noise = 564;
		float k = 1.0909f;
		
		
		int[] sample = GetData(path);
		int r = 220;
		int x = 261;
		int y = 257;
		
		int[] masksimg = mask(r , x, y, sample);
		int tem = 0;
		int l = 2*r;
		width = height = l;
		
		int[] samplefloat = new int[width*height];
		
		for(int i = 0; i< l*l; i++){
			
		tem =  masksimg[i];
		tem -= noise;
		if(tem<0)
				tem=0;

		tem = (int)((tem*k*256)/4000);		
		
//		samplefloat[i] = (tem/2000.0f);
//		samplefloat[i] = (tem*256/4000.0f);
		samplefloat[i] = tem;
//		samplefloat[i] = (255<<24)|(tem<<16)|(tem<<8)|tem;
		
	}
		
		
		
		BufferedImage new_img = new BufferedImage(width,height,BufferedImage.TYPE_BYTE_GRAY);
		
		WritableRaster raster = new_img.getRaster();
		raster.setSamples(0, 0, width, height,0, samplefloat);
		
		
//		Image img3 = Toolkit.getDefaultToolkit().createImage( new MemoryImageSource(width ,height ,samplefloat, 0, width)); 
//		Graphics2D g = (Graphics2D)new_img.getGraphics();
//		new_img.getGraphics().drawImage(img3, 0, 0, null);
		
		
		
		new_img = rotate(61.1,new_img);
		
		
		
//		raster.setSamples(0, 0, width, height, 0, samplefloat);
//		raster.setPixels(0, 0, width, height, samplefloat);
//		raster.setSamples(0, 0, width, height,0, sample);
//		raster.setSamples(0, 0, width, height,0, masksimg);
//		BufferedImage grayImage = new BufferedImage(width,height,BufferedImage.TYPE_BYTE_GRAY);
//		Graphics2D g = grayImage.createGraphics();
//		g.drawImage(grayImage, null,null);
		try {
			
		File file = new File(path4);
		if (!file.exists())
			file.createNewFile();
		
		ImageIO.write(new_img, "jpg", file);

	} catch (RuntimeException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
		
	}

	public static BufferedImage rotate(double angdeg, BufferedImage new_img){
		
		AffineTransform transform = AffineTransform.getRotateInstance(Math
				.toRadians(360-angdeg), new_img.getWidth()/2, new_img.getHeight()/2 );
		AffineTransformOp op = new AffineTransformOp(transform,
				AffineTransformOp.TYPE_BILINEAR);
		
		BufferedImage filteredImage = new BufferedImage(new_img.getWidth(), new_img
				.getHeight(), new_img.getType());
		op.filter(new_img, filteredImage);
		new_img = filteredImage;

		return new_img;
	}
	/**
	 * @param r
	 * @param x
	 * @param y
	 * @param img
	 * @return
	 */
	public static int[] mask(int r , int x, int y , int[] img){
		
		// (x,y):圆心坐标;  r: 半径; img：512*512图像
		//在matlab中,坐标从(1,1)开始，故此处(x,y)都减1
		x-=1;
		y-=1;
		int[] mask2 = new int[4*r*r];
		int x0 = 0;
		int y0 = 0;
		
		int tem = 0;
		y0 = y-r; 
//		y0 = y-r;
		//直径
		int l = 2*r ;
		for(int i = 0; i< l; i++){
			
			y0++;
//			x0 = x-r+1;
			x0 = x-r;
			for(int j= 0; j< l; j++){

				x0++;
				tem = img[y0*512+x0];
				if((Math.pow(x0-x,2)+ Math.pow(y0-y,2))>=Math.pow(r,2))
					mask2[i*l + j] = 0;
				else
					mask2[i*l + j] = tem;
			}
		}
		
		return mask2;
	}
	/*
	 * 图像之间的转化
	 * */
	public static void matrix()throws Exception{
		
		String path = "e:/N20031223G062731.img";
		String path2 = "e:/N20031223G062731.jpg";
		String path3 = "e:/05.jpg";
		String path4 = "e:/051.jpg";
		
		//灰度转换
		BufferedImage old_img = ImageIO.read(new File(path3));
		
		BufferedImage new_img = new BufferedImage(old_img.getWidth(),old_img .getHeight(),BufferedImage.TYPE_BYTE_GRAY);
		new_img.getGraphics().drawImage(old_img , 0, 0, null);

		ImageIO.write(new_img, "jpg", new File(path4));
		
		byte pix[] = new byte[1];
		int n = new_img.getWidth();
		int m = new_img.getHeight();
		/*double[][] matrix = new double[n][m];
		 
		     //swips the rows
		     for (int row = 0; row < n; ++row) {
			//swips the columns
		         for (int col = 0; col < m; ++col) {
		        	 
		          //matrix[row][col] = new_img.getRGB(row, col);
		        	 
//		           new_img.getRaster().getDataElements(row, col, pix);
//		           matrix[row][col] = pix[0];
		           matrix[row][col] = new_img.getRaster().getSample(row, col, 0);
		        	 
		           System.out.println("row " + row + " col " + col + " pixel " + matrix[row][col]);                     
			  }
		 }	*/
		
	}	
	/**
	 * 灰度转换
	 * @throws Exception
	 */
	public static void CreateGrayImage()throws Exception{
		
		int x = 0;
		int y = 0;
		int width = 512;
		int height = 512; 
		
		String path = "e:/N20031223G062731.img";
		String path2 = "e:/N20031223G062731.jpg";
		String path3 = "e:/05.jpg";
		String path4 = "e:/051.jpg";
		
		BufferedImage img = ImageIO.read(new File(path3));
		width = img.getWidth();
		height = img.getHeight();
        int[] pixels = GetPixels(img,x,y,width,height);
//		int[] pixels = GetData(path);
		
		Image img3 = Toolkit.getDefaultToolkit().createImage( new MemoryImageSource(width ,height ,pixels, 0, width)); 
		
		BufferedImage img2 = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
		Graphics g = img2.getGraphics();
//		g.clearRect(0, 0, width, height);

//		img.getGraphics().clearRect(0, 0, width, height);
		g.drawImage(img3,0,0,null);   		
		
		ImageIO.write(img2, "jpg", new File(path4));
		
	}
	
	/**
	 * 读取图像灰度值
	 * @param img
	 * @param x
	 * @param y
	 * @param w
	 * @param h
	 */
	public static int[] GetPixels(Image img,int x,int y,int w,int h)	{ 
		
	int[]pixels=new int[w*h]; 
	int gray;
	PixelGrabber pg=new PixelGrabber(img,x,y,w,h,pixels,0,w);
	
	try {
		
		pg.grabPixels();
		
	} catch (InterruptedException e) {
		// TODO �Զ���� catch ��
		e.printStackTrace();
	} 

	  for(int   j=0;j<h;j++)   
      {   
          for(int   i=0;i<w;i++)   
          {   
              gray=(int)(((pixels[w*j+i]>>16)&0xff)*0.8);   
              gray+=(int)(((pixels[w*j+i]>>8)&0xff)*0.1);   
              gray+=(int)(((pixels[w*j+i])&0xff)*0.1);   
        	  
              pixels[w*j+i]=(255<<24)|(gray<<16)|(gray<<8)|gray;       
          }   
      }   
//	Image   pic= Toolkit.getDefaultToolkit().createImage(new   MemoryImageSource(w,h,pixels,0,w));   //������ֵ����ͼ��   
//     Bufg.drawImage(pic,0,0,this);   
//	for(intj=0;j> 16)&0xff)*0.3);
//	gray+=(int)(((pixels[w*j+i]>>8)&0xff)*0.59);
//	gray+=(int)(((pixels[w*j+i] )&0xff)*0.11);
//	pixels[w*j+i]=(255<<24)|(gray<<16)|(gray<<8)|gray;

	  return pixels;
	}

	public static int[] GetData(String FileName) throws Exception {
		RandomAccessFile rFile = new RandomAccessFile(FileName, "r");
		
//		ArrayList<Short> arraylist = new ArrayList<Short>();
//		int[][] result = new int[512][512];
		int[] result = new int[512*512];
		long point = rFile.length() - 512*512*2;
		int i = 0, j = 0;
		rFile.seek(point);
		while (rFile.getFilePointer() < rFile.length()) {
			long p = rFile.getFilePointer();
			if (p < point)
				rFile.readByte();
			else {
//				result[i++] = rFile.readUnsignedShort();
//				result[i][j++] = rFile.readUnsignedShort();
				result[i++] = getByte(rFile.readByte(),rFile.readByte());
				}
			}

		rFile.close();
		return result;
	}

	public static int getByte(byte a,byte b){
		return (int) ((b& 0xFF)*256+ (a & 0xFF));	
	}


	public static byte[] getBytes(String FileName)throws Exception{
		
		RandomAccessFile rFile = new RandomAccessFile(FileName, "r");
		long point = rFile.length() - 512*512*2;
		int i = 0, j = 0;
		rFile.seek(point);
		byte[] result = new byte[512*512*2];
		
		rFile.readFully(result);
		return result;
        }
	
}